package org.csu.petstore.ssm.controller;

import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;

import org.csu.petstore.ssm.entity.Account;
import org.csu.petstore.ssm.entity.Cart;
import org.csu.petstore.ssm.entity.Consignee;
import org.csu.petstore.ssm.entity.Order;
import org.csu.petstore.ssm.service.AccountService;
import org.csu.petstore.ssm.service.OrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;

import java.io.IOException;
import java.util.List;

@Controller
//@RequestMapping("/order")
public class OrderController {
    @Autowired
    HttpSession httpSession;
    @Autowired
    AccountService accountService;
    @Autowired
    OrderService orderService;

    private Account account;
    private Order order;
    private Cart cart;

    @PostMapping("/confirmOrder")
    public String confirmOrder(Model model){
        Order order = (Order)httpSession.getAttribute("order");
//        Account account = (Account)session.getAttribute("account");
        model.addAttribute(order);
        return "order/confirmOrder";
    }

    @GetMapping("/listOrder")
    public String listOrder(){
        return "order/listOrders";
    }

    @GetMapping("/newOrder")
    public String newOrder(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        HttpSession session = request.getSession();
        account = (Account)session.getAttribute("loginAccount");
        cart = (Cart)session.getAttribute("cart");

        if(account == null){
           return "account/signon";
        }

            String username = account.getUserid();
            //AccountService accountService = new AccountService();
            List<Consignee> consigneeList = accountService.getConsignee(username);
            //List<Order> orderList = orderService.getOrders(username);
            session.setAttribute("consigneeList",consigneeList);
            //session.setAttribute("orderList",orderList);

            order = new Order();
            order.initOrder(account, cart);
            session.setAttribute("order", order);

        return "order/newOrders";
    }

    @GetMapping("/shippingForm")
    public String shippingForm(){
        return "order/shippingForm";
    }

    @GetMapping("/viewOrder")
    public String viewOrder(Model model, HttpServletRequest request) {
//        HttpSession session = request.getSession();
//        Order order = (Order) session.getAttribute("order"); // 确保使用 session 获取
        model.addAttribute("order", order);

//        session.removeAttribute("cart");
//        model.addAttribute("cart", null);

        return "order/viewOrder";
    }

}
